package com.tlgen.fragment;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rxjava.rxlife.RxLife;
import com.tlgen.R;
import com.tlgen.adapter.IdcardRecyclerViewAdapter;
import com.tlgen.bean.BaseFragment;
import com.tlgen.bean.Credit;
import com.tlgen.bean.CreditResult;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import rxhttp.RxHttp;

import static android.content.Context.MODE_PRIVATE;

public class IdCardFragment extends BaseFragment {

    private View view;

    private RecyclerView recyclerView;

    //定义以credit实体类为对象的数据集合
    private ArrayList<Credit> creditArrayList = new ArrayList<Credit>();

    //自定义recyclerView的适配器
    private IdcardRecyclerViewAdapter recyclerViewAdapter;

    String content;

    public static IdCardFragment newInstance(String content) {
        return new IdCardFragment().setContent(content);
    }

    public IdCardFragment setContent(String content) {
        this.content = content;
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_idcard;
    }

    @Override
    protected void initViews() {

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_idcard, container, false);
        initRecyclerView();
        return view;
    }

    private void sendGet() {
        // 通过 getSharedPreferences 获取当前用户的token
        String token = getActivity().getSharedPreferences("login_info", MODE_PRIVATE).getString("token", "");
        System.out.println("当前用户登录的token: " + token);
        String userName = getActivity().getSharedPreferences("login_info", MODE_PRIVATE).getString("userName", "");
        RxHttp.get("/student/credit/data/list?userName=" + userName)
                .addHeader("Authorization", token) // 携带token的请求头
                .asClass(CreditResult.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(result -> {
                    ArrayList<Credit> arrayList = new ArrayList<>();
                    for (int i = 0; i < result.getRows().size(); i++) {
                        arrayList.add(result.getRows().get(i));
                        // 保存结果
                        SharedPreferences.Editor editor = getActivity().getSharedPreferences("arrayListValue", MODE_PRIVATE).edit();
                        Gson gson = new Gson();
                        String json = gson.toJson(arrayList);
                        // System.out.println("保存的json为: "+ json);
                        editor.putString("arrayList", json);
                        editor.commit();
                    }
                }, (error)  -> {
                    System.out.println(error);
                });
    }

    private void initRecyclerView() {
        //获取RecyclerView
        recyclerView = view.findViewById(R.id.idcard_fragment);
        sendGet(); // 先发送请求
        initData(); // 再初始化数据
        // System.out.println("initRecyclerView中的ArrayList: " + creditArrayList); // 确认在创建适配器前是否有值
        //创建adapter
        recyclerViewAdapter = new IdcardRecyclerViewAdapter(getActivity(), creditArrayList);
        //给RecyclerView设置adapter
        recyclerView.setAdapter(recyclerViewAdapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        //RecyclerView中没有item的监听事件，需要自己在适配器中写一个监听事件的接口。参数根据自定义
        recyclerViewAdapter.setOnItemClickListener(new IdcardRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, Credit data) {
                //此处进行监听事件的业务处理
                Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initData() {
        SharedPreferences preferences = getActivity().getSharedPreferences("arrayListValue", MODE_PRIVATE);
        String json = preferences.getString("arrayList", null);
        System.out.println("获取到的json为: " + json);
        if (json != null)
        {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Credit>>(){}.getType();
            ArrayList<Credit> arrayList = new ArrayList<Credit>();
            arrayList = gson.fromJson(json, type);
            creditArrayList = arrayList;
        }
    }

/*    @Override
    public void onDestroy() {
        super.onDestroy();
    }*/
}
